from tkinter import Tk, Canvas, colorchooser, Frame, Button, filedialog
from PIL import Image

def choose_rgb_color():
    color = colorchooser.askcolor()
    return color[1] if color is not None else "#000000"

def choose_color(event):
    x = event.x // cell_size
    y = event.y // cell_size
    color = choose_rgb_color()
    canvas.itemconfig(cells[x][y], fill=color)

def get_most_common_color(image, x, y):
    pixels = image.load()
    color_counts = {}
    for i in range(cell_size):
        for j in range(cell_size):
            color = tuple(int(pixels[(x * cell_size) + i, (y * cell_size) + j][k]) for k in (0, 1, 2))
            if color in color_counts:
                color_counts[color] += 1
            else:
                color_counts[color] = 1
    most_common_color = max(color_counts, key=color_counts.get)
    return "#%02x%02x%02x" % most_common_color

def generate_image():
    img = Image.new("RGB", (512, 512))
    pixels = img.load()
    for x in range(10):
        for y in range(10):
            color = canvas.itemcget(cells[x][y], "fill")
            for i in range(cell_size):
                for j in range(cell_size):
                    pixels[(x * cell_size) + i, (y * cell_size) + j] = tuple(int(color.lstrip("#")[k:k+2], 16) for k in (0, 2, 4))
    img.show()

def export_image():
    img = Image.new("RGB", (512, 512))
    pixels = img.load()
    for x in range(10):
        for y in range(10):
            color = canvas.itemcget(cells[x][y], "fill")
            for i in range(cell_size):
                for j in range(cell_size):
                    pixels[(x * cell_size) + i, (y * cell_size) + j] = tuple(int(color.lstrip("#")[k:k+2], 16) for k in (0, 2, 4))
    filename = "milk.png"
    img.save(filename)

def import_image():
    filename = filedialog.askopenfilename(filetypes=[("Image Files", "*.png;*.jpg;*.jpeg;*.gif")])
    if filename:
        img = Image.open(filename)
        img = img.resize((cell_size*10, cell_size*10))
        pixels = img.load()
        for x in range(10):
            for y in range(10):
                color = get_most_common_color(img, x, y)
                canvas.itemconfig(cells[x][y], fill=color)

root = Tk()
cell_size = 51

frame = Frame(root)
frame.pack()

canvas = Canvas(frame, width=cell_size*10, height=cell_size*10)
canvas.pack()

cells = [[None] * 10 for _ in range(10)]

for x in range(10):
    for y in range(10):
        cell = canvas.create_rectangle(x * cell_size, y * cell_size, (x+1) * cell_size, (y+1) * cell_size, fill="#000000")
        canvas.tag_bind(cell, "<Button-1>", choose_color)
        cells[x][y] = cell

generate_button = Button(frame, text="Generate", command=generate_image)
generate_button.pack(side="left", padx=5)

export_button = Button(frame, text="Export", command=export_image)
export_button.pack(side="left", padx=5)

import_button = Button(frame, text="Import", command=import_image)
import_button.pack(side="left", padx=5)

root.mainloop()
